<template>
  <div class="settings-area">
    <div class="settings-header">
      <h2>{{ $t('settings.title') }}</h2>
      <div class="header-actions">
        <el-button type="primary" size="small" @click="saveSettings">
          <el-icon><Check /></el-icon>
          {{ $t('common.save') }} (Ctrl+S)
        </el-button>
        <el-button text @click="$emit('close')">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </div>
    
    <div class="settings-content">
      <!-- 设置页面 -->
      <!-- General -->
      <div class="settings-section">
        <h3>General</h3>
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-title">{{ $t('settings.language') }}</div>
            <div class="setting-description">{{ $t('settings.languageDesc') }}</div>
          </div>
          <el-select v-model="language" size="small" style="width: 120px" @change="onLanguageChange">
            <el-option 
              v-for="(lang, code) in languageOptions" 
              :key="code" 
              :label="lang" 
              :value="code" 
            />
          </el-select>
        </div>
        <!-- 编辑器设置 -->
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-title">{{ $t('settings.editorSettings') }}</div>
            <div class="setting-description">{{ $t('settings.editorSettingsDesc') }}</div>
          </div>
          <el-button type="primary" size="small">{{ $t('settings.open') }}</el-button>
        </div>
      </div>
      
      <!-- Preferences -->
      <div class="settings-section">
        <h3>Preferences</h3>
        
        <!-- SIMION路径设置 -->
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-title">{{ $t('settings.simionPath') }}</div>
            <div class="setting-description">{{ $t('settings.simionPathDesc') }}</div>
          </div>
          <div class="setting-control">
            <el-input v-model="simionPath" :placeholder="$t('placeholders.selectFile')" readonly style="width: 300px; margin-right: 8px;">
              <template #append>
                <el-button @click="selectSimionPath">{{ $t('settings.selectFile') }}</el-button>
              </template>
            </el-input>
          </div>
        </div>
        
        <!-- 扫描类型选择 -->
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-title">{{ $t('settings.scanType') }}</div>
            <div class="setting-description">{{ $t('settings.scanSettings') }}</div>
          </div>
          <el-radio-group v-model="scanType" @change="onScanTypeChange">
            <el-radio label="frequency">{{ $t('settings.frequencyScan') }}</el-radio>
            <el-radio label="voltage">{{ $t('settings.voltageScan') }}</el-radio>
          </el-radio-group>
        </div>
        
        <!-- 频率扫描参数 -->
        <div v-if="scanType === 'frequency'" class="setting-item">
          <div class="setting-info">
            <div class="setting-title">{{ $t('settings.frequencyParams') }}</div>
            <div class="setting-description">{{ $t('settings.scanSettings') }}</div>
          </div>
          <div class="setting-control">
            <div class="param-row">
              <el-input v-model="frequencyStart" :placeholder="$t('placeholders.startValue')" style="width: 150px; margin-right: 12px;" />
              <el-input v-model="frequencyStop" :placeholder="$t('placeholders.stopValue')" style="width: 150px; margin-right: 12px;" />
              <el-input v-model="frequencyStep" :placeholder="$t('placeholders.stepValue')" style="width: 150px; margin-right: 12px;" />
              <el-tag v-if="frequencyLength > 0" type="info">{{ $t('settings.scanLength') }}: {{ frequencyLength }}</el-tag>
            </div>
          </div>
        </div>
        
        <!-- 电压扫描参数 -->
        <div v-if="scanType === 'voltage'" class="setting-item">
          <div class="setting-info">
            <div class="setting-title">{{ $t('settings.voltageParams') }}</div>
            <div class="setting-description">{{ $t('settings.scanSettings') }}</div>
          </div>
          <div class="setting-control">
            <div class="param-row">
              <el-input v-model="voltageStart" :placeholder="$t('placeholders.startValue')" style="width: 150px; margin-right: 12px;" />
              <el-input v-model="voltageStop" :placeholder="$t('placeholders.stopValue')" style="width: 150px; margin-right: 12px;" />
              <el-input v-model="voltageStep" :placeholder="$t('placeholders.stepValue')" style="width: 150px; margin-right: 12px;" />
              <el-tag v-if="voltageLength > 0" type="info">{{ $t('settings.scanLength') }}: {{ voltageLength }}</el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { showMessage } from '@/utils/common'
import { useGlobalSettingsStore } from '@/stores/globalSettings'

const { t } = useI18n()

// Emits
const emit = defineEmits<{
  close: []
}>()

// 获取全局设置store
const globalSettings = useGlobalSettingsStore()


// 设置页面数据
const language = ref(globalSettings.language)

// 语言选项
const languageOptions = computed(() => {
  return {
    'zh-CN': t('languages.zh-CN'),
    'ja-JP': t('languages.ja-JP'), 
    'en-US': t('languages.en-US')
  }
})

// 全局参数 - 使用computed确保响应式
const simionPath = computed({
  get: () => globalSettings.simionPath,
  set: (value: string) => globalSettings.setSimionPath(value)
})
const scanType = computed({
  get: () => globalSettings.scanType,
  set: (value: 'frequency' | 'voltage') => globalSettings.setScanType(value)
})
const frequencyStart = computed({
  get: () => globalSettings.frequencyStart,
  set: (value: string) => {
    globalSettings.setFrequencyParams(value, globalSettings.frequencyStop, globalSettings.frequencyStep)
  }
})
const frequencyStop = computed({
  get: () => globalSettings.frequencyStop,
  set: (value: string) => {
    globalSettings.setFrequencyParams(globalSettings.frequencyStart, value, globalSettings.frequencyStep)
  }
})
const frequencyStep = computed({
  get: () => globalSettings.frequencyStep,
  set: (value: string) => {
    globalSettings.setFrequencyParams(globalSettings.frequencyStart, globalSettings.frequencyStop, value)
  }
})
const voltageStart = computed({
  get: () => globalSettings.voltageStart,
  set: (value: string) => {
    globalSettings.setVoltageParams(value, globalSettings.voltageStop, globalSettings.voltageStep)
  }
})
const voltageStop = computed({
  get: () => globalSettings.voltageStop,
  set: (value: string) => {
    globalSettings.setVoltageParams(globalSettings.voltageStart, value, globalSettings.voltageStep)
  }
})
const voltageStep = computed({
  get: () => globalSettings.voltageStep,
  set: (value: string) => {
    globalSettings.setVoltageParams(globalSettings.voltageStart, globalSettings.voltageStop, value)
  }
})

// 计算扫描长度
const frequencyLength = computed(() => {
  const start = parseFloat(frequencyStart.value)
  const stop = parseFloat(frequencyStop.value)
  const step = parseFloat(frequencyStep.value)
  
  // 如果开始值和停止值相同，返回1
  if (!isNaN(start) && !isNaN(stop) && start === stop) {
    return 1
  }
  
  // 如果步长为空或无效，但开始值和停止值不同，返回0
  if (isNaN(step) || step <= 0) {
    return 0
  }
  
  if (isNaN(start) || isNaN(stop)) return 0
  return Math.floor((stop - start) / step) + 1
})

const voltageLength = computed(() => {
  const start = parseFloat(voltageStart.value)
  const stop = parseFloat(voltageStop.value)
  const step = parseFloat(voltageStep.value)
  
  // 如果开始值和停止值相同，返回1
  if (!isNaN(start) && !isNaN(stop) && start === stop) {
    return 1
  }
  
  // 如果步长为空或无效，但开始值和停止值不同，返回0
  if (isNaN(step) || step <= 0) {
    return 0
  }
  
  if (isNaN(start) || isNaN(stop)) return 0
  return Math.floor((stop - start) / step) + 1
})

// 选择SIMION路径
const selectSimionPath = () => {
  if ((window as any).electronAPI) {
    (window as any).electronAPI.selectFile({
      filters: [
        { name: '可执行文件', extensions: ['exe'] },
        { name: '所有文件', extensions: ['*'] }
      ]
    }).then((result: any) => {
      if (!result.canceled && result.filePaths && result.filePaths.length > 0) {
        const selectedPath = result.filePaths[0]
        simionPath.value = selectedPath
        showMessage.success(t('messages.simionPathSet'))
      } else {
        showMessage.error(t('messages.fileSelectionFailed'))
      }
    }).catch((error: any) => {
      showMessage.error(t('messages.fileSelectionError') + ': ' + error.message)
    })
  } else {
    showMessage.warning(t('messages.fileSelectionUnavailable'))
  }
}

// 语言变化处理
const onLanguageChange = (newLanguage: 'zh-CN' | 'ja-JP' | 'en-US') => {
  globalSettings.setLanguage(newLanguage)
  language.value = newLanguage // 更新本地值
  showMessage.success(t('messages.languageUpdated'))
}

// 扫描类型变化处理
const onScanTypeChange = () => {
  // 切换扫描类型时清空另一个类型的参数
  if (scanType.value === 'frequency') {
    voltageStart.value = ''
    voltageStop.value = ''
    voltageStep.value = ''
  } else {
    frequencyStart.value = ''
    frequencyStop.value = ''
    frequencyStep.value = ''
  }
}

// 保存设置
const saveSettings = () => {
  // 数据已经通过computed的双向绑定自动保存到store
  showMessage.success(t('messages.settingsSaved'))
}


// 键盘事件处理
const handleKeydown = (event: KeyboardEvent) => {
  if (event.ctrlKey && event.key === 's') {
    event.preventDefault()
    saveSettings()
  }
}

// 生命周期
onMounted(() => {
  console.log('SettingsPanel mounted')
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.settings-area {
  flex: 1;
  background: #1e1e1e;
  color: #cccccc;
  overflow-y: auto;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #3e3e42;
  background: #2d2d30;
}

.settings-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.settings-content {
  padding: 24px;
  max-width: 800px;
}

.settings-section {
  margin-bottom: 32px;
}

.settings-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #3e3e42;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-info {
  flex: 1;
  margin-right: 16px;
}

.setting-title {
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  margin-bottom: 4px;
}

.setting-description {
  font-size: 12px;
  color: #888;
  line-height: 1.4;
}

.setting-control {
  display: flex;
  align-items: center;
}

.param-row {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}
</style>
